//用户名和密码验证库
import passport from 'koa-passport';
import LocalStrategy from 'passport-local';


import UserModel from '../../dbs/models/users';

passport.use(new LocalStrategy(async function (username, password, done) {
  let where = {
    username
  }

  //查询用户
  let res = await UserModel.findOne(where);

  if (res !== null) {
    //比对数据库密码和用户输入密码
    if (res.password === password) {
      return done(null, res);
    } else {
      return done(null, false, '密码错误');
    }
  } else {
    return done(null, false, '用户不存在')
  }
}));

//用户登录的时候把用户信息(序列化)存入session
passport.serializeUser(function (user, done) {
  done(null, user);
})

//反序列化操作
passport.deserializeUser(function (user, done) {
  return done(null, user);
})

export default passport;
